﻿using System;
using System.Configuration;
using System.Text;
using System.Windows;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using ClientApp.UtilClasses;

namespace ClientApp
{
    class Program
    {
        static byte[] bytes = new byte[1024];
        static Socket senderSock;
        private static string ipv4;
        private static int port;
        private Thread mListeningThread;
        private Thread mMonitoringThread;

        public static string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                //if (ip.AddressFamily == AddressFamily.InterNetwork)
                if (ip.IsIPv6LinkLocal == false && ip.AddressFamily== AddressFamily.InterNetwork)
                {

                    if(Convert.ToInt32(ip.ToString().Split('.')[0]) < 100)
                        return ip.ToString();
                }
            }
            throw new Exception("Local IP Address Not Found!");
        }


        static void Main(string[] args)
        {
            string peerName = GeneralHelperFunctions.ParentDirectoryNameExtractor();

            string ipAddress = GetLocalIPAddress();
            string port = ConfigurationManager.AppSettings["MyPort"];

            Console.WriteLine(ipAddress +"---"+ port);
            //peername,ip:port
            string toSend = (int)Communication.UtilClass.CommandsToSendList.CLIENT_ON_NETWORK+","+ ipAddress + ":" + port + "|" + peerName;
            Communication.Communication.SendCommandToServer(toSend);
            Console.WriteLine("Handshaked with server");
            Client_Life_Cycle.ClientProgram program = new Client_Life_Cycle.ClientProgram();
            Console.WriteLine("Client waiting");
             
            while(program.mListeningThread.IsAlive)
            {
                Thread.Sleep(5000);
            }
        }
    }
}
